package cn.kgc.spring.factory;

import com.mysql.jdbc.Driver;
import org.springframework.beans.factory.FactoryBean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author 课工场
 * @date 2024/11/5
 * @description  通过实现FactoryBean接口的形式  实现从spring容器中获取复杂类型对象
 *
 * FactoryBean<Connection>   T  表示该类需要返回的对象类型
 */
public class ConnectionFactoryBean implements FactoryBean<Connection> {


    //  托管该类后从spring中获取的对象
    @Override
    public Connection getObject() throws Exception {
        System.out.println("---------getObject()------------");

        String url = "jdbc:mysql:///java2426";
        String username = "root";
        String password = "root";
        try {
            Driver driver = new Driver();
            DriverManager.registerDriver(driver);
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Class<?> getObjectType() {
        return  Connection.class;
    }
}
